package com.younio.local.compnent.datasource;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentSkipListSet;

@Slf4j
public class MultiDataSourceHolder {

    /**
     * 记录当前线程使用的数据源
     */
    private static final ThreadLocal<String> context = new ThreadLocal<>();

    /**
     * 记录某个方法对应的数据源,用作缓存,在aspect中就不用作复杂的判断
     */
    private static final ConcurrentMap<Method, String> methodDsMap = new ConcurrentHashMap<>();

    private static final ConcurrentSkipListSet<String> datasource = new ConcurrentSkipListSet<>();

    static void add(String ds) {
        if (contains(ds)) {
            throw new IllegalArgumentException("Datasource " + ds + " already exist.");
        }
        datasource.add(ds);
    }

    private static boolean contains(String ds) {
        return datasource.contains(ds);
    }

    static void put(Method method, String ds) {
        methodDsMap.put(method, get(ds));
    }

    static String get(String ds) {
        if (!contains(ds)) {
            throw new IllegalArgumentException("Datasource " + ds + " is not exist.");
        }
        return ds;
    }

    static boolean contains(Method method) {
        return methodDsMap.containsKey(method);
    }

    static String get(Method method) {
        return methodDsMap.get(method);
    }

    static void set(String k) {
        context.set(k);
    }

    public static String get() {
        return context.get();
    }


    public static void clear() {
        context.remove();
        methodDsMap.clear();
        datasource.clear();
    }
}
